package com.sunbeam.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sunbeam.domain.User;
import com.sunbeam.exception.UserIsExistException;
import com.sunbeam.service.LoginService;
import com.sunbeam.service.impl.LoginServiceImpl;
import com.sunbeam.utils.WebUtils;
import com.sunbeam.web.form.LoginForm;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/servlet/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static LoginService loginService=new LoginServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//1.校验数据合法性
		LoginForm loginForm=WebUtils.form2Bean(request, LoginForm.class);
		System.out.println(loginForm.getUsername());
		boolean b=loginForm.validate();
		if(!b){
			request.setAttribute("loginForm", loginForm);
			request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request, response);
			return;
		}
		//2.将数据封装到bean
		User user=WebUtils.copyBeans(User.class, loginForm);
		user.setId(WebUtils.generateID());
		
		//3.注册操作
		try {
			loginService.register(user);
			request.setAttribute("message","注册成功！！");
			request.getRequestDispatcher("/WEB-INF/jsp/message/info.jsp").forward(request, response);
		} catch (UserIsExistException e) {
			loginForm.getErrorMsgMap().put("username", "该用户名已经存在！！");
			request.getRequestDispatcher("/WEB-INF/jsp/register.jsp").forward(request, response);
		}
	}

}
